﻿using System;
using System.Collections.Generic;
using MediaPortal.Configuration;
using MediaPortal.GUI.Library;
using MediaPortal.Player;
using MediaPortal.Dialogs;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;

namespace MyNetflix2
{
    [PluginIcons("MyNetflix2.Plugin.NetFlix.png", "MyNetflix2.Plugin.NetFlixDisabled.png")]
    public class MyNetFlixMain : ItemProcessor, ISetupForm
    {
        #region Locals

        public enum FacadeView {Users, Home, Disc, InstantMenu, AtHome, Recommendations, InstantDetail, RentalMenu, RentalHistoryAll, RentalHistoryWatched, RentalHistoryShipped, RentalHistoryReceived, Season, Episode, OData, Discs, RSS, Search }
        private Form _mpForm;
        private Process _instantMovie = null;
        private Microsoft.Win32.RegistryKey regkeyScreenSaver;
        private object origScreenSaveSetting;
        private delegate void RefreshQueueDelegate();
        private  bool _selectMode = false;
        private string _strMessage = "";

        public FacadeView CurrentView
        {
            get { return _currentView; }
        }
        
        #endregion

        #region Constructor

        public MyNetFlixMain()
        { }

        ~MyNetFlixMain()
        {}

        #endregion

        #region Overridden Methods

        /// <summary>
        /// Init()
        /// </summary>
        /// <returns></returns>
        public override bool Init()
        {
            ThreadPool.SetMinThreads(1200, 1200);
            _conn.GenerateRequestToken(_conn.GetDefaultUser());
            //--------------------------------------------------------------------------------
            // Load the netflix user
            //--------------------------------------------------------------------------------
            _user = new User(_conn.NetFlixAccessToken, _conn);
            _user.GetUser();
 
            //--------------------------------------------------------------------------------
            // Load the Users
            //--------------------------------------------------------------------------------
            _queueUsers = _conn.GetQueueUsers();
            _instantUsers = _conn.GetInstantUsers();

            //--------------------------------------------------------------------------------
            // Load up the queues
            //--------------------------------------------------------------------------------
            Thread loadQueues = new Thread(LoadQueues);
            loadQueues.Start();

            Log.Info("My NetFlix - MyNetFlixMain:Init: My NetFlix Loaded");
            return Load(GUIGraphicsContext.Skin + @"\MyNetFlix.xml");
        }

        /// <summary>
        /// DeInit()
        /// </summary>
        public override void DeInit()
        {
            base.DeInit();
        }

        /// <summary>
        /// OnPageLoad()
        /// </summary>
        protected override void OnPageLoad()
        {
            //--------------------------------------------------------------------------------
            // Set the current layout
            //--------------------------------------------------------------------------------
            _dummyLabel.Visible = false;
            _facadeQueue.View = GUIFacadeControl.ViewMode.List;
            GUIPropertyManager.SetProperty("#username", _user.FirstName);
            RefreshQueueDelegate refresh = new RefreshQueueDelegate(RefreshQueues);
            refresh.BeginInvoke(null, null);


            //--------------------------------------------------------------------------------
            // If a queue exists, lets load it up instead of the 'home' menu
            //--------------------------------------------------------------------------------
            if (_facadeQueueHold != null && _facadeQueueHold.Count > 0)
                GetPrevious();
            else
                LoadHomeMenu();
        }

        /// <summary>
        /// When the select button is clicked, lets catch the events...
        /// </summary>
        /// <param name="controlId">The control id</param>
        /// <param name="control">GUIControl control</param>
        /// <param name="actionType">Action Type</param>
        protected override void OnClicked(int controlId, GUIControl control, MediaPortal.GUI.Library.Action.ActionType actionType)
        {
            if (_selectMode)
                return;

            //--------------------------------------------------------------------------------
            // Lets see which control had the action
            //--------------------------------------------------------------------------------
            switch (controlId)
            {
                case 2:
                    ShowViewMenu();
                    break;
                case 3:
                    ShowTopXMenu();
                    break;
                case 4:
                    #region NetFlix Search
                    Search search = new Search(_user);

                    //--------------------------------------------------------------------------------
                    // Since this is a search, lets clear all the prior history
                    //--------------------------------------------------------------------------------
                    ClearQueues();

                    switch (ShowSearchOptions())
                    {
                        case 1:
                            GetStringFromKeyboard(ref _strMessage);
                            SetView(FacadeView.Search);
                            LoadFacadeControl(search.Refresh(_strMessage), _currentView);
                            SetFirst((QueueItem)_facadeQueue[0].TVTag, _currentView, true);
                            break;
                        case 2:
                            GetStringFromKeyboard(ref _strMessage);
                            SetView(FacadeView.Search);
                            LoadFacadeControl(search.Refresh("InstantTitleSearch", "", _strMessage), _currentView);
                            SetFirst((QueueItem)_facadeQueue[0].TVTag, _currentView, true);
                            break;
                        case 3:
                            GetStringFromKeyboard(ref _strMessage);
                            SetView(FacadeView.Search);
                            LoadFacadeControl(search.Refresh("InstantTitleTVSeriesSearch", "", _strMessage), _currentView);
                            SetFirst((QueueItem)_facadeQueue[0].TVTag, _currentView, true);
                            break;
                        case 4:
                            ShowSearchGenreOptions(ref _strMessage);
                            SetView(FacadeView.Search);
                            LoadFacadeControl(search.Refresh("InstantGenreSearch", _strMessage, ""), _currentView);
                            SetFirst((QueueItem)_facadeQueue[0].TVTag, _currentView, true);
                            break;
                        case 5:
                            Person person = new Person(_user);
                            GetStringFromKeyboard(ref _strMessage);
                            SetView(FacadeView.Search);
                            LoadFacadeControl(person.Refresh(_strMessage), _currentView);
                            SetFirst((QueueItem)_facadeQueue[0].TVTag, _currentView, true);
                           break;
                    }

                    //--------------------------------------------------------------------------------
                    // Show the small detail pane
                    //--------------------------------------------------------------------------------
                    _dummyLabel.Visible = true;

                    break;

                    #endregion

                case 5:
                    ShowNewReleaseMenu();
                    break;
                case 6:
                    ShowUpcomingReleaseMenu();
                    break;

                case 50:
                    #region Listview control operation
                    //--------------------------------------------------------------------------------
                    // This is the facade control
                    //--------------------------------------------------------------------------------

                    //--------------------------------------------------------------------------------
                    // If the TVTag is null, then lets instanciate a new instance of the QueueItem
                    //--------------------------------------------------------------------------------
                    if (_facadeQueue.SelectedListItem.TVTag == null)
                        _facadeQueue.SelectedListItem.TVTag = new QueueItem();

                    switch (_facadeQueue.SelectedListItem.TVTag.GetType().Name)
                    {
                        case "QueueItem":
                            #region Queue Selections

                            int iSelectedItem = _facadeQueue.SelectedListItemIndex;
                            QueueItem queue_item = (QueueItem)_facadeQueue.SelectedListItem.TVTag;
                            GUIListItem queue_list_item = _facadeQueue.SelectedListItem;
                            FacadeView myFacadeView;

                            //--------------------------------------------------------------------------------
                            // Lets see which view we're currently in
                            //--------------------------------------------------------------------------------
                            switch (_currentView)
                            {
                                #region Users View

                                case FacadeView.Users:
                                    _conn.GenerateRequestToken(_facadeQueue.SelectedListItem.Label);
                                    //--------------------------------------------------------------------------------
                                    // Load the netflix user
                                    //--------------------------------------------------------------------------------
                                    _user = new User(_conn.NetFlixAccessToken, _conn);
                                    _user.GetUser();

                                    //--------------------------------------------------------------------------------
                                    // Load up the queues
                                    //--------------------------------------------------------------------------------
                                    Thread loadQueues = new Thread(RefreshQueues);
                                    loadQueues.Start();
                                    LoadHomeMenu();
                                    break;

                                #endregion

                                #region Home View
 
                                case FacadeView.Home:
                                    //--------------------------------------------------------------------------------
                                    // We're at the home Menu
                                    //--------------------------------------------------------------------------------

                                    //----------------------------------------------------------------------------------------------------------
                                    // if a user cant watch instant movies, the selected items will be off by 1 since there is no Instant Queue
                                    //----------------------------------------------------------------------------------------------------------
                                    if (!_user.CanInstantWatch)
                                        if (iSelectedItem > 0)
                                            iSelectedItem++;

                                    //--------------------------------------------------------------------------------
                                    // Now lets see which home menu item is selected
                                    // 0 = disc queue
                                    // 1 = Instant queue
                                    // 2 = At Home queue
                                    // 3 = Rental History
                                    // 4 = Recommendations
                                    //--------------------------------------------------------------------------------
                                    switch (iSelectedItem)
                                    {
                                        case 0:
                                        case 2:
                                        case 3:
                                            //--------------------------------------------------------------------------------
                                            // Lets load the items directly into the facade control
                                            //--------------------------------------------------------------------------------
                                            SavePrevious(_facadeQueue, _facadeQueue.SelectedListItemIndex, _currentView);

                                            myFacadeView = new FacadeView();
                                            
                                            switch (iSelectedItem)
                                            {
                                                case 0:
                                                    myFacadeView = FacadeView.Disc;
                                                    break;
                                                case 2:
                                                    myFacadeView = FacadeView.AtHome;
                                                    break;
                                                case 3:
                                                    myFacadeView = FacadeView.Recommendations;
                                                    break;
                                            }

                                            LoadFacadeControlQI(iSelectedItem, myFacadeView);
                                            SetFirst((QueueItem)_facadeQueue[0].TVTag, myFacadeView, true);
                                            break;

                                        case 1:
                                            //---------------------------------------------------------------------------------------------
                                            // Call the Instnat Menu to display the users if there are more than one.
                                            //---------------------------------------------------------------------------------------------
                                            LoadInstantUserMenu();
                                            break;

                                        case 4:
                                            //---------------------------------------------------------------------------------------------
                                            // Call the Rental History menu, then let the users select which history they want to see
                                            //---------------------------------------------------------------------------------------------
                                            LoadRentalHistoryMenu();
                                            break;
                                    }

                                    break;

                                #endregion

                                #region Instant Movies

                                case FacadeView.InstantMenu:
                                    LoadInstantQueue(_facadeQueue.SelectedListItem.Label);
                                    break;

                                #endregion

                                #region Rental History View
                                //--------------------------------------------------------------------------------
                                // We're at the Rental Menu
                                //--------------------------------------------------------------------------------
                                case FacadeView.RentalMenu:
                                    SavePrevious(_facadeQueue, _facadeQueue.SelectedListItemIndex, _currentView);

                                    //--------------------------------------------------------------------------------
                                    // Lets get the history items from NetFlix and load the facade control
                                    //--------------------------------------------------------------------------------
                                    Queue historyQueue = new RentalHistory(_user);
                                    myFacadeView = new FacadeView();

                                    switch (iSelectedItem)
                                    {
                                        case 0:
                                            myFacadeView = FacadeView.RentalHistoryAll;
                                            break;
                                        case 1:
                                           myFacadeView = FacadeView.RentalHistoryReceived;
                                            break;
                                        case 2:
                                           myFacadeView = FacadeView.RentalHistoryShipped;
                                            break;
                                        case 3:
                                           myFacadeView = FacadeView.RentalHistoryWatched;
                                            break;
                                    }

                                    LoadFacadeControl(historyQueue.Refresh(iSelectedItem), myFacadeView);
                                    SetFirst((QueueItem)_facadeQueue[0].TVTag, myFacadeView, true);
                                    break;

                                #endregion

                                #region Movie/Series View

                                case FacadeView.Disc:
                                case FacadeView.InstantDetail:
                                case FacadeView.RentalHistoryAll:
                                case FacadeView.RentalHistoryReceived:
                                case FacadeView.RentalHistoryShipped:
                                case FacadeView.RentalHistoryWatched:
                                case FacadeView.Season:
                                case FacadeView.Recommendations:
                                case FacadeView.Search:
                                case FacadeView.RSS:
                                case FacadeView.OData:
                                    //--------------------------------------------------------------------------------
                                    // If its a series, lets get the series queue
                                    //--------------------------------------------------------------------------------
                                    if (queue_item.IsSeries && _currentView != FacadeView.Season && _currentView != FacadeView.Episode && queue_item.SeasonsLink != null)
                                    {
                                        //--------------------------------------------------------------------------------
                                        // Save the previous queue and load the seasons menu
                                        //--------------------------------------------------------------------------------
                                        SavePrevious(_facadeQueue, _facadeQueue.SelectedListItemIndex, _currentView);
                                        LoadSeasonMenu(queue_item.SeasonsLink);
                                    }
                                    else if ((_currentView == FacadeView.Season && queue_item.EpisodesLink != null && queue_item.IsInstant) || (queue_item.IsSeries && queue_item.SeasonsLink == null && queue_item.EpisodesLink != null && queue_item.IsInstant))
                                    {
                                        //--------------------------------------------------------------------------------
                                        // Load the episodes queue
                                        //--------------------------------------------------------------------------------
                                        SavePrevious(_facadeQueue, _facadeQueue.SelectedListItemIndex, _currentView);
                                        Episodes episodes = new Episodes(_user);
                                        LoadFacadeControl(episodes.Refresh(queue_item.EpisodesLink, queue_item.TheTVDbId), FacadeView.Episode);
                                        SetFirst((QueueItem)_facadeQueue[0].TVTag, FacadeView.Episode, true);
                                    }
                                    else if ((_currentView == FacadeView.Season || _currentView == FacadeView.Search) && queue_item.DiscLink != null)
                                    {
                                        //--------------------------------------------------------------------------------
                                        // This is a series, but no instant watch, so lets show the discs available
                                        //--------------------------------------------------------------------------------
                                        SavePrevious(_facadeQueue, _facadeQueue.SelectedListItemIndex, _currentView);
                                        Discs discs = new Discs(_user);
                                        LoadFacadeControl(discs.Refresh(queue_item.DiscLink), FacadeView.Disc);
                                        SetFirst((QueueItem)_facadeQueue[0].TVTag, FacadeView.Discs, false);
                                    }
                                    else if (queue_item.IsInstant)
                                    {
                                        PlayMovie(queue_list_item);
                                    }
                                    break;
                                case FacadeView.Episode:
                                    PlayMovie(queue_list_item);
                                    break;

                                #endregion
                            }
                            break;
                            #endregion

                        case "ODataItem":
                            #region OData Selections

                            ODataItem odata_item = (ODataItem)_facadeQueue.SelectedListItem.TVTag;
                            GUIListItem odata_list_item = _facadeQueue.SelectedListItem;

                            //--------------------------------------------------------------------------------
                            // Lets see which view we're currently in
                            //--------------------------------------------------------------------------------
                            switch (_currentView)
                            {
                                case FacadeView.OData:
                                    //--------------------------------------------------------------------------------
                                    // Save prior queue
                                    //--------------------------------------------------------------------------------
                                    SavePrevious(_facadeQueue, _facadeQueue.SelectedListItemIndex, _currentView);

                                    //--------------------------------------------------------------------------------
                                    // If this is a season, lets look at the episodes. If not play the selection
                                    //--------------------------------------------------------------------------------
                                    if (odata_item.IsSeries && odata_item.IsInstant && _currentView != FacadeView.Season && _currentView != FacadeView.Episode && odata_item.SeasonsLink != null)
                                    {
                                        Episodes episodes = new Episodes(_user);
                                        LoadFacadeControl(episodes.Refresh(odata_item.TitleRef + "/episodes", odata_item.TheTVDbId), FacadeView.Episode);
                                        SetFirst((ODataItem)_facadeQueue[0].TVTag, FacadeView.Episode, true);
                                    }
                                    if (odata_item.IsSeries && !odata_item.IsInstant)
                                    {
                                        Discs discs = new Discs(_user);
                                        LoadFacadeControl(discs.Refresh(odata_item.TitleRef + "/discs"), FacadeView.Disc);
                                        SetFirst((QueueItem)_facadeQueue[0].TVTag, FacadeView.Discs, true);
                                    }
                                    else if (odata_item.IsInstant)
                                        PlayMovie(odata_list_item);
                                    break;
                            }
                            break;
                            #endregion

                    }
                    break;

                    #endregion
            }
        }

        /// <summary>
        /// When a button is pressed, lets catch the action.
        /// </summary>
        /// <param name="action"></param>
        public override void OnAction(MediaPortal.GUI.Library.Action action)
        {
            //Log.Info("Action Button" + action.wID.ToString());
            QueueItem queue_item = null;
            try
            {
                queue_item = (QueueItem)_facadeQueue.SelectedListItem.TVTag;
            }
            catch { }

            if (_instantMovie != null && !(_instantMovie.HasExited))
            {
                #region Actions Performed while watching a movie

                IntPtr NetflixWindowHandle = FindWindow(null, "Microsoft Silverlight");

                //--------------------------------------------------------------------------------------
                // Verify that silverlight is running. If not, get the web browser handle and check it
                //--------------------------------------------------------------------------------------
                if (NetflixWindowHandle == IntPtr.Zero)
                {
                    NetflixWindowHandle = _instantMovie.Handle;

                    //--------------------------------------------------------------------------------------
                    // Verify that browser is running
                    //--------------------------------------------------------------------------------------
                    if (NetflixWindowHandle == IntPtr.Zero)
                        return;
                }
                
                SetForegroundWindow(NetflixWindowHandle);

                switch (action.wID)
                {
                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_PAUSE:
                        //--------------------------------------------------------------------------------------
                        // Send the pause command
                        //--------------------------------------------------------------------------------------
                        SendKeys.SendWait("{PGDN}");
                        Log.Debug("My NetFlix:MyNetFlixMain:OnAction : {PGDN}");
                        break;
                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_PLAY:
                        //--------------------------------------------------------------------------------------
                        // Send the pause command
                        //--------------------------------------------------------------------------------------
                        SendKeys.SendWait("{PGUP}");
                        Log.Debug("My NetFlix:MyNetFlixMain:OnAction : {PGUP}");
                        break; 
                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_PREVIOUS_MENU:
                        //--------------------------------------------------------------------------------------
                        // Send the ESCAPE full screen command
                        //--------------------------------------------------------------------------------------
                        SendKeys.SendWait("{ESC}");
                        Log.Debug("My NetFlix:MyNetFlixMain:OnAction : {ESC}");
                      break;
                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_SELECT_ITEM:
                        //--------------------------------------------------------------------------------------
                        // Send the Enter command
                        //--------------------------------------------------------------------------------------
                        SendKeys.SendWait("{ENTER}");
                        Log.Debug("My NetFlix:MyNetFlixMain:OnAction : {ENTER}");
                         break;
                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_CONTEXT_MENU:
                        //--------------------------------------------------------------------------------------
                        // Send the full screen command
                        //--------------------------------------------------------------------------------------
                        SendKeys.SendWait("f");
                        Log.Debug("My NetFlix:MyNetFlixMain:OnAction : f");
                         break;
                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_STOP:
                         Log.Debug("My NetFlix:MyNetFlixMain:OnAction : Stop");
                        _instantMovie.Kill();
                        _instantMovie = null;
                        break;
                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_REWIND:
                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_MOVE_LEFT:
                        //--------------------------------------------------------------------------------------
                        // Send the pause command
                        //--------------------------------------------------------------------------------------
                        SendKeys.SendWait("+{LEFT}");
                        Log.Debug("My NetFlix:MyNetFlixMain:OnAction : +{LEFT}");
                         break;

                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_FORWARD:
                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_MOVE_RIGHT:
                        //--------------------------------------------------------------------------------------
                        // Send the pause command
                        //--------------------------------------------------------------------------------------
                        SendKeys.SendWait("+{RIGHT}");
                        Log.Debug("My NetFlix:MyNetFlixMain:OnAction : +{RIGHT}");
                       break;
                }

                #endregion
            }
            else
            {
                #region Actions Performed while NOT watching a movie

                switch (action.wID)
                {

                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_STOP:
                        #region Stop Button
                        //------------------------------------------------------------------------------------------------
                        // Reset screen saver setting
                        //------------------------------------------------------------------------------------------------
                        regkeyScreenSaver.SetValue("ScreenSaveActive", origScreenSaveSetting);

                        if (_mpForm.TopMost)
                            _mpForm.Visible = true;

                        _instantMovie = null;
                        _mpForm = null;

                        break;

                        #endregion

                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_PREVIOUS_MENU:
                        #region Previous Button

                        switch (_currentView)
                        {
                            case FacadeView.Home:
                                if (_queueUsers.Count > 1)
                                    LoadUsersMenu();
                                break;
                            case FacadeView.Disc:
                            case FacadeView.RentalMenu:
                            case FacadeView.Recommendations:
                            case FacadeView.AtHome:
                            case FacadeView.OData:
                            case FacadeView.RSS:
                                LoadHomeMenu();
                                break;
                            case FacadeView.RentalHistoryAll:
                            case FacadeView.RentalHistoryReceived:
                            case FacadeView.RentalHistoryShipped:
                            case FacadeView.RentalHistoryWatched:
                                LoadRentalHistoryMenu();
                                break;
                            case FacadeView.InstantMenu:
                                LoadHomeMenu();
                                break;
                            case FacadeView.InstantDetail:
                                if (_instantUsers.Count == 1)
                                    LoadHomeMenu();
                                else
                                    LoadInstantUserMenu();
                                break;
                            case FacadeView.Season:
                            case FacadeView.Episode:
                            case FacadeView.Discs:
                                GetPrevious();
                                break;
                            default:
                                base.OnAction(action);
                                break;
                        }
                        break;

                        #endregion

                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_MOVE_DOWN:
                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_MOVE_UP:
                        #region Up & Down Buttons

                        bool bMoving = false;

                        switch (_currentView)
                        {
                            case FacadeView.Disc:
                                if (action.wID == MediaPortal.GUI.Library.Action.ActionType.ACTION_MOVE_UP && _facadeQueue.SelectedListItem.Selected)
                                {
                                    bMoving = true;

                                    if (_facadeQueue.SelectedListItemIndex == 0)
                                    {
                                        NotifyUser("Move Error", "Cannot move disc above top of queue");
                                        break;
                                    }
                                    _facadeQueue.MoveItemUp(_facadeQueue.SelectedListItemIndex, true);
                                }
                                if (action.wID == MediaPortal.GUI.Library.Action.ActionType.ACTION_MOVE_DOWN && _facadeQueue.SelectedListItem.Selected)
                                {
                                    bMoving = true; 
                                    
                                    if (_facadeQueue.SelectedListItemIndex < _facadeQueue.Count - 1)
                                    {
                                        QueueItem nextQueueItem = (QueueItem)_facadeQueue[_facadeQueue.SelectedListItemIndex + 1].TVTag;
                                        if (nextQueueItem.Availability == "saved")
                                        {
                                            NotifyUser("Move Error", "Cannot move disc below saved movies");
                                            break;
                                        }
                                    }
                                    _facadeQueue.MoveItemDown(_facadeQueue.SelectedListItemIndex, true);

                                }
                                break;
                        }


                        if (_facadeQueue.Focus && _facadeQueue.Visible)
                        {
                            if (!bMoving)
                                base.OnAction(action);
                            GUIPropertyManager.SetProperty("#movieof", (_facadeQueue.SelectedListItemIndex + 1).ToString());
                        }
                        else
                        {
                            base.OnAction(action);
                            GUIPropertyManager.SetProperty("#movieof", (_facadeQueue.SelectedListItemIndex + 1).ToString());
                        }
                        break;

                        #endregion

                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_SELECT_ITEM:
                        #region Select Button

                        switch (_currentView)
                        {
                            case FacadeView.Disc:
                                
                                if (_facadeQueue.SelectedListItem.Selected)
                                {
                                    _facadeQueue.SelectedListItem.Selected = false;
                                    _myQueue = new DiscQueue(_user);
                                    try
                                    {
                                        _myQueue.Add(queue_item.TitleRef, RestCalls.DiscFormat.NONE, _facadeQueue.SelectedListItemIndex + 1);
                                    }
                                    catch (Exception ex)
                                    {
                                        Log.Error("My NetFlix:MyNetFlixMain:OnAction: Error - " + ex.Message);
                                    }
                                }
                                break;

                            default:
                                if (_selectMode)
                                {
                                    if (_facadeQueue.SelectedListItem.Selected)
                                        _facadeQueue.SelectedListItem.Selected = false;
                                    else
                                        _facadeQueue.SelectedListItem.Selected = true;
                                }
                                break;
                        }
                        if (!_selectMode) ;
                            base.OnAction(action);
                        break;

                        #endregion

                    case MediaPortal.GUI.Library.Action.ActionType.ACTION_RECORD:
                        #region Record Button

                        switch (_facadeQueue.SelectedListItem.Selected)
                        {
                            case true:
                                switch (_currentView)
                                {
                                    case FacadeView.OData:
                                    case FacadeView.InstantDetail:
                                    case FacadeView.Recommendations:
                                        _facadeQueue.SelectedListItem.Selected = false;
                                        break;

                                }
                                break;

                            case false:
                                switch (_currentView)
                                {
                                    case FacadeView.Disc:
                                        if(queue_item.Availability != "saved")
                                            _facadeQueue.SelectedListItem.Selected = true;
                                        break;
                                    default:
                                        if (_selectMode)
                                        {
                                            _selectMode = false;
                                            ClearSelections();
                                        }
                                        else
                                        {
                                            _selectMode = true;
                                            NotifyUser("Select Mode", "You have entered select mode");
                                        }
                                        break;
                                }
                                break;


                        }
                        break;

                        #endregion

                    default:
                        base.OnAction(action);
                        break;
                }
                #endregion
            }

        }
        
        /// <summary>
        /// OnPageDestroy()
        /// </summary>
        /// <param name="new_windowId"></param>
        protected override void OnPageDestroy(int new_windowId)
        {
            base.OnPageDestroy(new_windowId);
            SavePrevious(_facadeQueue, _facadeQueue.SelectedListItemIndex, _currentView);
        }

        #endregion

        #region Misc Calls (PlayMovie, Load & Refresh Queues, SetFirst)


        /// <summary>
        /// Get the number of selected items in the queue
        /// </summary>
        /// <returns></returns>
        private int GetNumberOfSelectedItems()
        {
            int iNoSelectedItems = 0;

            for (int i = 0; i < _facadeQueue.Count; i++)
            {
                if (_facadeQueue[i].Selected)
                    iNoSelectedItems++;
            }

            return iNoSelectedItems;
        }

        /// <summary>
        /// Play the movie
        /// </summary>
        private void PlayMovie(GUIListItem info)
        {
            QueueItem queueItem = null;
            ODataItem odataItem = null;
            string titleRef = "";
            string title = "";
            string coverId = "";

            switch (info.TVTag.GetType().Name)
            {
                case "QueueItem":
                    queueItem = (QueueItem)info.TVTag;
                    titleRef = queueItem.TitleRef;
                    title = queueItem.Title;
                    coverId = queueItem.CoverId;
                    break;
                case "ODataItem":
                    odataItem = (ODataItem)info.TVTag;
                    titleRef = odataItem.TitleRef;
                    title = odataItem.Title;
                    coverId = odataItem.CoverId;
                    break;
            }

            if (g_Player.IsTimeShifting || g_Player.IsVideo || g_Player.IsMusic)
                g_Player.Stop();

            if (_instantMovie == null || _instantMovie.HasExited)
            {
                try
                {
                    // ------------------------------------------------------------------------------------------------
                    //  Add the movie to the watched list and refresh the list.
                    //------------------------------------------------------------------------------------------------
                    _conn.AddMovieWatched(coverId);
                    _lstWatchedMovies.Clear();
                    _lstWatchedMovies = _conn.GetWatchedMovies();
                    _facadeQueue.SelectedListItem.IsPlayed = true;

                    // ------------------------------------------------------------------------------------------------
                    //  Start the movie
                    //------------------------------------------------------------------------------------------------
                    _instantMovie = System.Diagnostics.Process.Start("IEXPLORE.EXE", "-k http://www.netflix.com/CommunityAPIPlay?movieid=http://api.netflix.com/catalog/movie/" + coverId);
                    Log.Info("MyNetFlixMain:ShowInstantQueueMenu: Playing Movie: " + title);

                    //------------------------------------------------------------------------------------------------
                    // Disable screen saver
                    //------------------------------------------------------------------------------------------------
                    regkeyScreenSaver = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Control Panel").OpenSubKey("Desktop", true);
                    origScreenSaveSetting = regkeyScreenSaver.GetValue("ScreenSaveActive");
                    regkeyScreenSaver.SetValue("ScreenSaveActive", "0");

                    //------------------------------------------------------------------------------------------------
                    // Lets sleep for 10 seconds, then put the movie in full screen
                    //------------------------------------------------------------------------------------------------
                    Thread.Sleep(10000);

                    IntPtr NetflixWindowHandle = _instantMovie.Handle;
                    SetWindowPos(NetflixWindowHandle, 0, Screen.AllScreens[_conn.DefaultScreen].Bounds.X, Screen.AllScreens[_conn.DefaultScreen].Bounds.Y, 0, 0, 3);

                    //--------------------------------------------------------------------------------------
                    // Verify that browser is running
                    //--------------------------------------------------------------------------------------
                    if (NetflixWindowHandle == IntPtr.Zero)
                        return;
                    SetForegroundWindow(NetflixWindowHandle);

                    //--------------------------------------------------------------------------------------
                    // Send the full screen command
                    //--------------------------------------------------------------------------------------
                    SendKeys.SendWait("f");

                    //--------------------------------------------------------------------------------------
                    //EndofMoviecheck();
                    //--------------------------------------------------------------------------------------
                    //Thread endMovieChecker = new Thread(EndofMoviecheck);
                    //endMovieChecker.Start();
                }
                catch (Exception ex)
                {
                    okDialog("My NetFlix", "Unable to Play. NetflixViewer.exe unavailable.");
                    return;
                }
            }
        }

        /// <summary>
        /// This is to display the OK dialog.
        /// </summary>
        private void okDialog(string header, string text)
        {
            GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK);
            dlgOk.SetHeading(header);
            dlgOk.SetLine(2, text);
            dlgOk.DoModal(GetID);
        }


        /// <summary>
        /// Check to see if a movie has stopped.
        /// </summary>
        private void EndofMoviecheck()
        {
            //---------------------------------------------------------------------------------------
            // Run until the movie ends, then quit
            //---------------------------------------------------------------------------------------
            for (; ; )
            {
                //---------------------------------------------------------------------------------------
                // Get the screen image
                //---------------------------------------------------------------------------------------
                Bitmap screenImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
                Graphics gx = Graphics.FromImage(screenImage); ;
                gx.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);

                //---------------------------------------------------------------------------------------
                // Get the image to compare to
                //---------------------------------------------------------------------------------------
                Bitmap savedImage = new Bitmap(Config.GetFolder(Config.Dir.Skin) + "\\Confluence\\Media\\NetFlixEndImage.png");

                //---------------------------------------------------------------------------------------
                // Dump both images to a bitmap to compare
                //---------------------------------------------------------------------------------------
                MemoryStream ms = new MemoryStream();
                screenImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                String screenBitmap = Convert.ToBase64String(ms.ToArray());
                ms.Position = 0;
                savedImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                String savedBitmap = Convert.ToBase64String(ms.ToArray());

                //---------------------------------------------------------------------------------------
                // Lets see if the saved image is contained within the first image
                //---------------------------------------------------------------------------------------
                if (screenBitmap.Contains(savedBitmap))
                {
                    //---------------------------------------------------------------------------------------
                    // It is, so lets kill the process and exit the loop
                    //---------------------------------------------------------------------------------------
                    _instantMovie.Kill();
                    _instantMovie = null;
                    break;
                }

                //---------------------------------------------------------------------------------------
                // Sleep for 5 seconds between checks
                //---------------------------------------------------------------------------------------
                Thread.Sleep(5000);
            }
        }

        #endregion

        #region ISetupForm Members

        /// <summary>
        /// Returns the name of the plugin which is shown in the plugin menu
        /// </summary>
        public string PluginName()
        {
            return "NetFlix";
        }


        /// <summary>
        /// Returns the description of the plugin is shown in the plugin menu 
        /// </summary>
        public string Description()
        {
            return "The My NetFlix Plugin allows you to add, update, delete Discs from your Disc Queue as well as your Instant Queue. It will also allow you to use the instant view features of NetFlix.";
        }

        /// <summary>
        /// Returns the author of the plugin which is shown in the plugin menu
        /// </summary>
        public string Author()
        {
            return "Wile E. Coyote";
        }

        /// <summary>
        /// show the setup dialog
        /// </summary>
        public void ShowPlugin()
        {
            MyNetFlixConfig configScreen = new MyNetFlixConfig();

            configScreen.ShowDialog();
        }

        /// <summary>
        /// Indicates whether plugin can be enabled/disabled
        /// </summary>
        public bool CanEnable()
        {
            return true;
        }

        /// <summary>
        /// Get Windows-ID
        /// </summary>
        public int GetWindowId()
        {
            // WindowID of windowplugin belonging to this setup
            // enter your own unique code
            return 10099;
        }

        /// <summary>
        /// Indicates if plugin is enabled by default;
        /// </summary>
        public bool DefaultEnabled()
        {
            return true;
        }

        /// <summary>
        /// indicates if a plugin has it's own setup screen
        /// </summary>
        public bool HasSetup()
        {
            return true;
        }

        /// <summary>
        /// If the plugin should have it's own button on the main menu of MediaPortal then it
        /// should return true to this method, otherwise if it should not be on home
        /// it should return false
        /// </summary>
        /// <param name="strButtonText">text the button should have</param>
        /// <param name="strButtonImage">image for the button, or empty for default</param>
        /// <param name="strButtonImageFocus">image for the button, or empty for default</param>
        /// <param name="strPictureImage">subpicture for the button or empty for none</param>
        /// <returns>true : plugin needs it's own button on home
        /// false : plugin does not need it's own button on home</returns>
        public bool GetHome(out string strButtonText, out string strButtonImage,
        out string strButtonImageFocus, out string strPictureImage)
        {
            strButtonText = PluginName();
            strButtonImage = String.Empty;
            strButtonImageFocus = String.Empty;
            strPictureImage = String.Empty;
            return true;
        }

        /// <summary>
        /// With GetID it will be an window-plugin / otherwise a process-plugin
        /// Enter the id number here again
        /// </summary>
        public override int GetID
        {
            get
            {
                return 10099;
            }

            set
            {
            }
        }

        #endregion
    }
}
